// nodejs 环境下获取微信公众号 access_token
// 安装axios、moment
// npm install axios moment --save

const fs = require("fs");
const path = require("path");
const axios = require("axios");
const moment = require("moment");

// 1.读token.json是否过期;
// 2.如果没过期就直接返回token的值;
// 3.如果过期就调用微信接口获取token并写入token.json;

const getToken = (params) => {
  return new Promise((resolve, reject) => {
    const tokenFile = path.join(__dirname, "token.json");
    fs.readFile(tokenFile, "utf-8", (err, data) => {
      if (err) {
        reject(err);
      } else {
        if (data) {
          const token = JSON.parse(data);
          if (token.expires_in > moment().unix()) {
            resolve(token.access_token);
            return;
          }
        }
      }

      const appid = params.appid;
      const secret = params.secret;

      axios
        .get(
          `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`
        )
        .then((res) => {
          if (res.data && res.data.errcode) {
            console.log(res.data);
            reject(data);
            return;
          }
          resolve(res.data.access_token);
          const t = res.data;
          t.expires_in = t.expires_in + moment().unix() - 1200;
          fs.writeFile(tokenFile, JSON.stringify(t), () => {
            if (err) {
              reject(err);
            }
          });
        });
    });
  });
};

module.exports = { getToken };
